package cn.wolfcode.interceptor;

import cn.wolfcode.annotation.RequireLogin;
import cn.wolfcode.cache.service.IUserInfoRedisService;
import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(!(handler instanceof HandlerMethod)){
            return true;
        }


//        String token = request.getHeader("token");
//        UserInfo user = userInfoRedisService.getUserByToken(token);
//        if(user == null){
//            //没有登录返回有登录提示界面
//            response.setContentType("application/json; charset=utf-8");
//            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
//            return false;
//        }

        //1.判断当前请求方法上是否有注解RequireLogin
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);

        //如果有进行登录验证
        if(handlerMethod.hasMethodAnnotation(RequireLogin.class)){
            if(user == null){
            //没有登录返回有登录提示界面
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
            return false;
            }
        }
        //如果没有放行
        return true;
    }
}
